//
//  SEGActivityTaskMainCell.m
//  Commom
//
//  Created by Clavis on 2020/7/23.
//

#import "SEGActivityTaskMainCell.h"

@interface SEGActivityTaskMainCell () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UILabel *processLabel;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray<SEGActivityTaskModel*> *taskModelArray;

@end

@implementation SEGActivityTaskMainCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIView *titleView = [[UIView alloc] init];
    [self.contentView addSubview:titleView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    UILabel *titleLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = @"任务中心";
        label.textColor = kColor_1;
        label.font = [UIFont boldSystemFontOfSize:15];
        [titleView addSubview:label];
        label;
    });
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_offset(0);
    }];
    
    self.processLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = @"进度0/0";
        label.textColor = kColor_3;
        label.font = kFont_13;
        [titleView addSubview:label];
        label;
    });
    [self.processLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.mas_offset(0);
    }];
    
    [self.contentView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(titleView.mas_bottom);
        make.height.mas_equalTo(110);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = kColor_bg;
    [self addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(5);
        make.left.right.bottom.mas_equalTo(0);
    }];
}

- (void)updateViewWithTaskModelArray:(NSArray<SEGActivityTaskModel*> *)taskModelArray {
    self.taskModelArray = taskModelArray;
    // 计算进度
    __block NSInteger alreayCompleteCount = 0;
    [self.taskModelArray enumerateObjectsUsingBlock:^(SEGActivityTaskModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.whetherComplete == 1) {
            alreayCompleteCount ++;
        }
    }];
    self.processLabel.text = @"";
    if (alreayCompleteCount > 0) {
        self.processLabel.text = [NSString stringWithFormat:@"进度%ld/%ld",(long)alreayCompleteCount,(long)self.taskModelArray.count];
    }
    // 刷新列表
    [self.collectionView reloadData];
}

#pragma mark - <UICollectionViewDelegate, UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.taskModelArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGActivityTaskSubCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SEGActivityTaskSubCell" forIndexPath:indexPath];
    [cell updateCellWithTaskModel:self.taskModelArray[indexPath.row] index:indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.clickBlock) {
        self.clickBlock(indexPath.row);
    }
}

#pragma mark - Getter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = CGSizeMake(200, 110);
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.minimumLineSpacing = 10;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = kColor_W;
        [_collectionView registerClass:[SEGActivityTaskSubCell class] forCellWithReuseIdentifier:@"SEGActivityTaskSubCell"];
        _collectionView.contentInset = UIEdgeInsetsMake(0, 15, 0, 15);
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}


@end

@interface SEGActivityTaskSubCell ()

@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *endTimeLabel;
@property (nonatomic, strong) UIView *operateBackView;
@property (nonatomic, strong) UILabel *operateLabel;
@property (nonatomic, strong) UILabel *priceTipLabel;
@property (nonatomic, strong) UILabel *numberLabel;

@end

@implementation SEGActivityTaskSubCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.backImageView = ({
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"bg_fulishe_list_01")];
        imageView.layer.cornerRadius = 5;
        imageView.layer.masksToBounds = YES;
        [self addSubview:imageView];
        imageView;
    });
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    
    UIView *titleBackTopView = [[UIView alloc] init];
    titleBackTopView.backgroundColor = kColor_S1;
    [self addSubview:titleBackTopView];
    
    UIView *titleBackView = [[UIView alloc] init];
    titleBackView.backgroundColor = kColor_S1;
    titleBackView.layer.cornerRadius = 3;
    [self addSubview:titleBackView];
    
    

    self.titleLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = @"每日打卡";
        label.textColor = kColor_W;
        label.font = kFont_11;
        label.backgroundColor = kColor_S1;
        label.textAlignment = NSTextAlignmentCenter;
        [titleBackView addSubview:label];
        label;
    });
    
    [titleBackTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(15);
        make.width.equalTo(titleBackView);
        make.height.mas_equalTo(9);
    }];
    
    [titleBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(15);
        make.height.mas_equalTo(18);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(0);
        make.left.mas_equalTo(5);
        make.right.mas_equalTo(-5);
        make.top.bottom.mas_equalTo(0);
    }];
    
    self.priceTipLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = @"奖";
        label.textColor = kColor_W;
        label.font = kFont_11;
        label.backgroundColor = kColor_S1;
        label.textAlignment = NSTextAlignmentCenter;
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 20, 18) byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(3,3)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = CGRectMake(0, 0, 20, 18);
        maskLayer.path = maskPath.CGPath;
        label.layer.mask = maskLayer;
        [self addSubview:label];
        label;
    });
    [self.priceTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleBackView.mas_right).offset(5);
        make.top.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(20, 18));
    }];
    
    self.numberLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.text = @"1";
        label.textColor = kColor_W;
        label.backgroundColor = kColor_1;
        label.font = kFont_12;
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 6;
        label.layer.masksToBounds = YES;
        [self addSubview:label];
        label;
    });
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(13);
        make.width.height.mas_equalTo(12);
    }];
    
    self.detailLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.text = @"邻里圈点赞";
        label.textColor = kColor_1;
        label.font = kFont_12;
        [self addSubview:label];
        label;
    });
    [self.detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.numberLabel);
        make.left.mas_equalTo(32);
        make.right.mas_equalTo(-10);
    }];
    
    self.priceLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.text = @"10元京东券";
        label.textColor = kColor_1;
        label.font = [UIFont boldSystemFontOfSize:16];
        [self addSubview:label];
        label;
    });
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.detailLabel.mas_bottom).offset(7);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-10);
    }];
    
    UIView *operateBackView = ({
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = kColor_W;
        view.layer.cornerRadius = 12;
        view.layer.shadowColor = kColor_1.CGColor;
        view.layer.shadowOffset = CGSizeMake(0,1);
        view.layer.shadowOpacity = 0.1;
        view.layer.shadowRadius = 4;
        view.layer.cornerRadius = 12;
        [self addSubview:view];
        view;
    });
    self.operateBackView = operateBackView;
    self.operateLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = @"去完成(10/30)";
        label.textColor = kColor_1;
        label.font = kFont_11;
        label.textAlignment = NSTextAlignmentCenter;
        [operateBackView addSubview:label];
        label;
    });
    [self.operateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(0);
    }];
    [operateBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.bottom.mas_equalTo(-10);
        make.width.mas_equalTo(84);
        make.height.mas_equalTo(24);
    }];
    
    self.endTimeLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = @"07-12结束";
        label.textColor = kColor_W;
        label.font = kFont_10;
        [self addSubview:label];
        label;
    });
    [self.endTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-17);
        make.left.mas_equalTo(15);
//        make.right.equalTo(operateBackView.mas_left).mas_offset(-10);
    }];
}

- (void)updateCellWithTaskModel:(SEGActivityTaskModel *)taskModel index:(NSInteger)index {
    // 1.任务标题 & 奖
    self.titleLabel.text = taskModel.mainTaskTopic;
    CGFloat titleMaxWidth = 190-30-10;
    if (taskModel.whetherShowLottery == 1) {
        self.priceTipLabel.hidden = NO;
        titleMaxWidth -= 25;
    } else {
        self.priceTipLabel.hidden = YES;
    }
    CGFloat titleWidth = ceil([taskModel.mainTaskTopic widthForFont:kFont_11]);
    CGFloat displayWidth = MIN(titleMaxWidth, titleWidth);
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(displayWidth);
    }];
    
    // 2.子任务内容 & 多个任务提示 ① & 子任务奖品名称
    if (taskModel.childTaskList.count > 1) {
        self.numberLabel.hidden = NO;
        [self.detailLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(32);
        }];
    } else {
        self.numberLabel.hidden = YES;
        [self.detailLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
        }];
    }
    self.detailLabel.text = @"";
    self.priceLabel.text = @"";
    if (taskModel.childTaskList.count > 0) {
        SEGActivityChildTaskModel *childModel = taskModel.childTaskList.firstObject;
        self.detailLabel.text = childModel.childTaskName;
        self.priceLabel.text = childModel.prizeName;
    }
    
    // 3.操作按钮
    self.operateLabel.textColor = kColor_1;
    self.operateBackView.backgroundColor = kColor_W;
    if (taskModel.whetherReceive == 2) {
        self.operateLabel.text = @"领取";
    } else {
        if (taskModel.whetherComplete == 1) {
            self.operateLabel.text = @"已完成";
            self.operateLabel.textColor = kColor_W;
            self.operateBackView.backgroundColor = kColor_L2;
        } else {
            NSString *labelString = @"去完成";
            /*
             任务状态
             1未领取：任务需手动领取，用户点击【去打卡】领取任务；
             2进行中：已领取未全部完成，【去打卡】按钮同步显示进度：如果是单个多次操作任务，显示：完成次数/总次数；如果是多个子任务的任务组，显示：已完子任务数/子任务总数；
             3完成次数/完成子任务数=0，不展示进度；
             已完成：已完成任务组所有子任务，且按钮置灰不支持点击；
             */
            if (taskModel.childTaskList.count > 1) {
                // 多个子任务并且有完成的任务 展示：完成任务数/子任务总数
                if (taskModel.completeChildTaskCount > 0) {
                    labelString = [labelString stringByAppendingFormat:@"(%ld/%ld)", (long)taskModel.completeChildTaskCount,(long)taskModel.childTaskList.count];
                }
            } else if (taskModel.childTaskCount == 1) {
                // 单个子任务&操作次数为多次&有完成的次数 展示：完成次数/总次数
                SEGActivityChildTaskModel *subTaskModel = taskModel.childTaskList.firstObject;
                if (subTaskModel.operateNum > 1 && subTaskModel.completeOperateCount > 0) {
                    labelString = [labelString stringByAppendingFormat:@"(%ld/%ld)",(long)subTaskModel.completeOperateCount, (long)subTaskModel.operateNum];
                }
            }
            self.operateLabel.text = labelString;
        }
    }
    
    // 4.日期
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:taskModel.endTime.longLongValue];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    self.endTimeLabel.text = [NSString stringWithFormat:@"%@结束",[formatter stringFromDate:date]];
    
    // 5.背景
    NSString *placeholderImageName = [NSString stringWithFormat:@"bg_fulishe_list_0%ld", (long)((index%4)+1)];
    UIImage *placehoderImage = [UIImage imageWithContentsOfFile:SEGPicName(placeholderImageName)];
    [self.backImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,taskModel.mainTaskBackgroundImage]] placeholderImage:placehoderImage];
}

@end
